<template>
  <view class="buddy-page">
    <!-- 全局发布弹框 -->
    <PublishModal ref="publishModalRef" />
    <!-- 顶部背景 -->
    <image class="header-image" src="/static/header-bg.png" mode="aspectFill"></image>

    <!-- 固定顶部区域 -->
    <view class="fixed-header">
      <view class="spacer"></view>
      
      <!-- Header Section -->
      <view class="header-content">
        <view class="location" @click="getCurrentLocation">
          <uni-icons type="location-filled" size="20" color="#333"></uni-icons>
          <text>{{ currentLocation || '定位中...' }}</text>
        </view>
        <view class="search-bar-wrapper">
          <view class="search-bar-container">
            <input class="search-input" placeholder="搜一搜" v-model="searchKeyword" @confirm="performSearch" />
            <view class="search-icon-btn" @click="performSearch">
              <uni-icons type="search" size="20" color="#666"></uni-icons>
            </view>
          </view>
        </view>
        <view class="header-icons">
          <image
            :src="modeIcon"
            class="mode-toggle-icon"
            mode="aspectFit"
            @click="toggleViewMode"
          />
        </view>
      </view>

      <!-- Tabs Section -->
      <view class="tabs">
        <scroll-view scroll-x class="tabs-scroll" :show-scrollbar="false">
          <view class="tabs-content">
            <text :class="{'tab-item': true, 'active': activeTab === 'all'}" @click="activeTab = 'all'">全部</text>
            <text 
              v-for="type in buddyTypes" 
              :key="type.id" 
              :class="{'tab-item': true, 'active': activeTab === type.id}" 
              @click="activeTab = type.id"
            >
              {{ type.typeName }}
            </text>
          </view>
        </scroll-view>
        <image src="/static/search.png" class="filter-tab-icon" mode="aspectFit" @click="toggleFilterModal"></image>
      </view>
    </view>

    <!-- 筛选弹框 -->
    <view v-if="showFilterModal" class="filter-modal-overlay" :style="{ top: filterModalTop }" @click="showFilterModal = false">
      <view class="filter-modal" @click.stop>
        <!-- 性别筛选 -->
        <view class="filter-section">
          <view class="filter-label">性别</view>
          <view class="filter-options">
            <view 
              v-for="option in genderOptions" 
              :key="option.value"
              :class="['filter-option', { 'filter-option-active': filterState.gender === option.value }]"
              @click="filterState.gender = option.value"
            >
              {{ option.label }}
            </view>
          </view>
        </view>

        <!-- 距离筛选 -->
        <view class="filter-section">
          <view class="filter-label">距离</view>
          <view class="filter-options">
            <view 
              v-for="option in distanceOptions" 
              :key="option.value"
              :class="['filter-option', { 'filter-option-active': filterState.distance === option.value }]"
              @click="filterState.distance = option.value"
            >
              {{ option.label }}
            </view>
          </view>
        </view>

        <!-- 费用筛选 -->
        <view class="filter-section">
          <view class="filter-label">费用</view>
          <view class="filter-options">
            <view 
              v-for="option in costOptions" 
              :key="option.value"
              :class="['filter-option', { 'filter-option-active': filterState.cost === option.value }]"
              @click="filterState.cost = option.value"
            >
              {{ option.label }}
            </view>
          </view>
        </view>

        <!-- 底部按钮 -->
        <view class="filter-footer">
          <view class="filter-btn filter-btn-reset" @click="resetFilter">重置</view>
          <view class="filter-btn filter-btn-confirm" @click="confirmFilter">确定</view>
        </view>
      </view>
    </view>

    <!-- Buddy List Section -->
    <scroll-view 
      v-if="!isMapMode"
      scroll-y 
      class="buddy-list"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <BuddyCard
        v-for="buddy in buddyData"
        :key="buddy.id"
        :buddy="buddy"
        :join-loading="joinLoadingId === buddy.id"
        @join="acceptBuddyOrder(buddy)"
      />
      <view v-if="loadStatus === 'loading'" class="loading-more">加载中...</view>
      <view v-if="loadStatus === 'noMore'" class="no-more">没有更多了</view>
    </scroll-view>
    <view v-else class="map-container">
      <map
        :key="`map-${isMapMode}`"
        id="buddyMap"
        class="buddy-map"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :markers="mapMarkers"
        :scale="12"
        :enable-scroll="true"
        :enable-zoom="true"
        show-location
        @updated="onMapUpdated"
        @regionchange="onMapRegionChange"
        @markertap="onMarkerTap"
      />
    </view>

    <!-- 地图弹框 -->
    <view v-if="showMapModal && selectedBuddy" class="map-modal-overlay" @click="closeMapModal">
      <view class="map-modal-content" @click.stop>
        <view class="map-modal-close" @click.stop="closeMapModal">
          <uni-icons type="close" size="24" color="#666"></uni-icons>
        </view>
        <view class="map-modal-buddy-card" @click.stop="goToDetailFromModal">
          <BuddyCard
            :buddy="selectedBuddy"
            :clickable="false"
            :join-loading="selectedBuddy && joinLoadingId === selectedBuddy.id"
            @join="acceptBuddyOrder(selectedBuddy)"
          />
        </view>
      </view>
    </view>
    </view>
    
    <!-- 自定义底部导航 -->
    <CustomTabBar />
  </template>
  
  <script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import PublishModal from '../components/PublishModal.vue';
import BuddyCard from './components/BuddyCard.vue';
import CustomTabBar from '../components/CustomTabBar.vue';
import BuddyApi from '@/sheep/api/member/buddy';

const activeTab = ref('all');
const publishModalRef = ref(null);
const currentLocation = ref('定位中...');
const currentLatitude = ref(null); // 用户当前纬度
const currentLongitude = ref(null); // 用户当前经度
const searchKeyword = ref('');
const buddyTypes = ref([]); // 搭子类型列表
const showFilterModal = ref(false); // 筛选弹框显示状态
const isMapMode = ref(false); // 列表 / 地图模式
const showMapModal = ref(false); // 地图弹框显示状态
const selectedBuddy = ref(null); // 选中的搭子数据
const joinLoadingId = ref(null); // 当前接单Loading的搭子ID

// 分页相关
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});
const loadStatus = ref('more'); // 'loading' | 'more' | 'noMore'
const refreshing = ref(false);

// 筛选选项
const genderOptions = [
  { label: '仅限女生', value: 'female' },
  { label: '仅限男生', value: 'male' },
  { label: '男女不限', value: 'all' },
];

const distanceOptions = [
  { label: '1km以内', value: '1' },
  { label: '3km以内', value: '3' },
  { label: '5km以内', value: '5' },
  { label: '10km以内', value: '10' },
  { label: '20km以内', value: '20' },
  { label: '50km以内', value: '50' },
];

const costOptions = [
  { label: '50以内', value: '0-50' },
  { label: '50-100', value: '50-100' },
  { label: '100-200', value: '100-200' },
  { label: '200-300', value: '200-300' },
  { label: '300-400', value: '300-400' },
  { label: '400-500', value: '400-500' },
  { label: '500以上', value: '500+' },
];

// 筛选状态
const filterState = ref({
  gender: 'all', // 默认男女不限
  distance: '', // 默认不限制
  cost: '', // 默认不限制
});

// 搭子列表数据
const buddyData = ref([]);
const rawBuddyData = ref([]);

const modeIcon = computed(() => isMapMode.value ? '/static/list.png' : '/static/map.png');

const toggleViewMode = async () => {
  // #ifdef H5
  let listHeight = 0;
  if (!isMapMode.value) {
    const buddyList = document.querySelector('.buddy-list');
    if (buddyList) {
      listHeight = buddyList.offsetHeight || buddyList.clientHeight;
    }
  }
  // #endif
  
  isMapMode.value = !isMapMode.value;
  if (isMapMode.value) {
    await nextTick();
    
    setTimeout(() => {
      // #ifdef H5
      const mapContainer = document.querySelector('.map-container');
      const mapEl = document.getElementById('buddyMap');
      
      if (mapContainer && mapEl) {
        const viewportHeight = window.innerHeight;
        // 固定头部高度：spacer(100) + header-content(约100) + tabs(约100) + 间距(约100) = 约400rpx
        // 转换为px（假设1rpx = 0.5px）
        const fixedHeaderHeight = 200; // 400rpx ≈ 200px
        const calculatedHeight = viewportHeight - fixedHeaderHeight;
        
        mapContainer.style.top = `${fixedHeaderHeight}px`;
        mapContainer.style.height = `${calculatedHeight}px`;
        mapEl.style.height = `${calculatedHeight}px`;
        mapEl.style.width = '100%';
      }
      // #endif
    }, 200);
  }
};

const onMapUpdated = (e) => {
  // #ifdef H5
  nextTick(() => {
    const mapContainer = document.querySelector('.map-container');
    const mapEl = document.getElementById('buddyMap');
    
    if (mapContainer && mapEl) {
      if (mapContainer.offsetHeight < 100 || mapEl.offsetHeight < 100) {
        const viewportHeight = window.innerHeight;
        // 固定头部高度约300rpx，转换为px（假设1rpx = 0.5px）
        const fixedHeaderHeight = 150; // 300rpx ≈ 150px
        const calculatedHeight = viewportHeight - fixedHeaderHeight;
        
        mapContainer.style.top = `${fixedHeaderHeight}px`;
        mapContainer.style.height = `${calculatedHeight}px`;
        mapEl.style.height = `${calculatedHeight}px`;
        mapEl.style.width = '100%';
      }
    }
  });
  // #endif
};

const onMapRegionChange = (e) => {
};

const onMarkerTap = (e) => {
  // 阻止默认行为，不显示地图自带的弹窗
  if (e && e.stopPropagation) {
    e.stopPropagation();
  }
  
  const markerId = e.detail?.markerId;
  if (!markerId) {
    return;
  }
  
  // 通过 markerId 找到对应的 marker
  const marker = mapMarkers.value.find(m => {
    // 匹配 id，或者如果是字符串格式的 marker_${index}，也尝试匹配
    return m.id === markerId || String(m.id) === String(markerId);
  });
  
  if (marker) {
    // 如果 marker 中有保存的原始数据，直接使用
    if (marker.data) {
      selectedBuddy.value = marker.data;
      showMapModal.value = true;
      return;
    }
    
    // 否则通过经纬度匹配
    const buddy = buddyData.value.find(item => {
      return item.latitude === marker.latitude && item.longitude === marker.longitude;
    });
    
    if (buddy) {
      selectedBuddy.value = buddy;
      showMapModal.value = true;
    }
  }
};

const closeMapModal = () => {
  showMapModal.value = false;
  selectedBuddy.value = null;
};

// 从地图弹框跳转到详情页
const goToDetailFromModal = () => {
  if (!selectedBuddy.value) {
    return;
  }
  
  const buddyId = selectedBuddy.value.id || selectedBuddy.value.orderId;
  if (buddyId) {
    closeMapModal(); // 先关闭弹框
    uni.navigateTo({
      url: `/pages/buddy/detail?id=${buddyId}`
    });
  }
};

// 接单
const acceptBuddyOrder = async (buddy) => {
  if (!buddy || joinLoadingId.value === buddy.id) {
    return;
  }

  const orderId = buddy.id;
  if (!orderId) {
    uni.showToast({
      title: '搭子信息缺失',
      icon: 'none'
    });
    return;
  }

  joinLoadingId.value = orderId;
  try {
    const res = await BuddyApi.acceptBuddyOrder({ buddyOrderId: orderId });
    if (res?.code === 0) {
      uni.showToast({
        title: '已提交参与申请',
        icon: 'success'
      });
      if (selectedBuddy.value && selectedBuddy.value.id === orderId) {
        closeMapModal();
      }
    } else {
      uni.showToast({
        title: res?.msg || '参与失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('接受搭子订单失败:', error);
    uni.showToast({
      title: '参与失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    joinLoadingId.value = null;
  }
};

const formatTime = (timeStr) => {
  if (!timeStr) return '';
  try {
    const date = new Date(timeStr);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
  } catch (e) {
    return timeStr;
  }
};

const formatDuration = (minutes) => {
  if (!minutes) return '';
  if (minutes < 60) {
    return `${minutes}分钟`;
  }
  const hours = Math.floor(minutes / 60);
  const mins = minutes % 60;
  if (mins === 0) {
    return `${hours}小时`;
  }
  return `${hours}小时${mins}分钟`;
};

const formatGenderLimit = (genderLimit) => {
  if (genderLimit === 1) return '仅限男生';
  if (genderLimit === 2) return '仅限女生';
  return '男女不限';
};

const calculateDistance = (lat1, lon1, lat2, lon2) => {
  if (lat1 === null || lat1 === undefined || lon1 === null || lon1 === undefined ||
      lat2 === null || lat2 === undefined || lon2 === null || lon2 === undefined) {
    return null;
  }
  
  const R = 6371000;
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;
  
  return distance;
};

const formatDistance = (distance) => {
  if (!distance && distance !== 0) return '';
  if (distance < 1000) {
    return `${Math.round(distance)}m`;
  }
  return `${(distance / 1000).toFixed(1)}km`;
};

const mapBuddyData = (item) => {
  const buddyType = buddyTypes.value.find(type => type.id === item.buddyTypeId);
  
  let distanceText = '';
  if (currentLatitude.value && currentLongitude.value && item.latitude && item.longitude) {
    const distance = calculateDistance(
      currentLatitude.value,
      currentLongitude.value,
      item.latitude,
      item.longitude
    );
    if (distance !== null) {
      distanceText = formatDistance(distance);
    }
  }
 
  const acceptUsers = Array.isArray(item.acceptUsers) ? item.acceptUsers : [];
  const hasAcceptUsersField = Array.isArray(item.acceptUsers);
  const participantAvatars = acceptUsers
    .map(user => user.avatar || '/static/avatars/default_avatar.png')
    .filter(Boolean);
  const participantsToShow = participantAvatars.slice(0, 5);
  const hasMoreParticipants = participantAvatars.length > 5;
  const participantsCount = hasAcceptUsersField
    ? acceptUsers.length
    : (item.participantCount || 0);

  return {
    id: item.id,
    avatar: item.publisherAvatar || '/static/avatars/default_avatar.png',
    name: item.publisherNickname || '匿名用户',
    rating: item.publisherRating || 0,
    publisherId: item.publisherId || item.userId || null, // 发布者用户ID
    title: item.title || '',
    buddyTypeName: buddyType?.typeName || '搭子',
    tag: buddyType?.typeName || '搭子',
    type: buddyType?.typeCode || 'default',
    typeId: item.buddyTypeId,
    date: item.startTime && item.startTime > 0 ? formatTime(item.startTime) : '待定',
    location: item.location || '',
    latitude: item.latitude ?? null,
    longitude: item.longitude ?? null,
    restrictions: formatGenderLimit(item.genderLimit),
    duration: formatDuration(item.duration),
    distance: distanceText,
    images: item.images || [],
    participants: participantsToShow,
    hasMoreParticipants,
    participantsCount,
    price: item.unitPrice || 0,
  };
};

const mapMarkers = computed(() => {
  return buddyData.value
    .filter(item => item.latitude !== null && item.latitude !== undefined && item.latitude !== '' &&
      item.longitude !== null && item.longitude !== undefined && item.longitude !== '')
    .map((item, index) => ({
      id: item.id || `marker_${index}`, // 使用唯一标识
      latitude: Number(item.latitude),
      longitude: Number(item.longitude),
      iconPath: '/static/map-icon.png', // 标记点图标路径
      width: 30,
      height: 30,
      callout: {
        display: 'NONE', // 完全禁用默认弹窗
      },
      data: item, // 保存原始数据引用，方便查找
    }));
});

const DEFAULT_CENTER = {
  latitude: 39.909187,
  longitude: 116.397451,
};

const mapCenter = computed(() => {
  if (currentLatitude.value && currentLongitude.value) {
    return {
      latitude: Number(currentLatitude.value),
      longitude: Number(currentLongitude.value),
    };
  }
  const firstMarker = mapMarkers.value[0];
  if (firstMarker) {
    return {
      latitude: firstMarker.latitude,
      longitude: firstMarker.longitude,
    };
  }
  return DEFAULT_CENTER;
});
const getBuddyTypeList = async () => {
  try {
    const res = await BuddyApi.getBuddyTypeList();
    if (res && res.code === 0 && res.data) {
      buddyTypes.value = res.data || [];
    }
  } catch (error) {
    console.error('获取搭子类型列表失败:', error);
  }
};

const getBuddyList = async () => {
  if (loadStatus.value === 'loading') {
    return;
  }
  
  loadStatus.value = 'loading';
  
  try {
    const params = {
      pageNo: pagination.value.pageNo,
      pageSize: pagination.value.pageSize,
    };
    
    if (activeTab.value !== 'all') {
      params.buddyTypeId = activeTab.value;
    }
    
    if (searchKeyword.value) {
      params.title = searchKeyword.value;
    }
    
    if (filterState.value.gender !== 'all') {
      const genderMap = {
        'male': 1,
        'female': 2,
      };
      params.genderLimit = genderMap[filterState.value.gender];
    }
    
    if (filterState.value.cost) {
      const costRange = filterState.value.cost.split('-');
      if (costRange.length === 2) {
        params.minPrice = parseFloat(costRange[0]);
        params.maxPrice = parseFloat(costRange[1]);
      } else if (filterState.value.cost === '500+') {
        params.minPrice = 500;
      } else if (filterState.value.cost === '0-50') {
        params.minPrice = 0;
        params.maxPrice = 50;
      }
    }
    
    const res = await BuddyApi.getBuddyOrderPage(params);
    
    if (res && res.code === 0 && res.data) {
      const list = res.data.list || [];
      
      if (pagination.value.pageNo === 1) {
        rawBuddyData.value = list;
      } else {
        rawBuddyData.value = [...rawBuddyData.value, ...list];
      }
      
      const mappedList = list.map(mapBuddyData);
      
      if (pagination.value.pageNo === 1) {
        buddyData.value = mappedList;
      } else {
        buddyData.value = [...buddyData.value, ...mappedList];
      }
      
      pagination.value.total = res.data.total || 0;
      loadStatus.value = buddyData.value.length < pagination.value.total ? 'more' : 'noMore';
    } else {
      loadStatus.value = 'noMore';
    }
  } catch (error) {
    console.error('获取搭子列表失败:', error);
    loadStatus.value = 'noMore';
  }
};

const loadMore = () => {
  if (loadStatus.value === 'noMore' || loadStatus.value === 'loading') {
    return;
  }
  pagination.value.pageNo++;
  getBuddyList();
};

const onRefresh = async () => {
  refreshing.value = true;
  pagination.value.pageNo = 1;
  pagination.value.total = 0;
  buddyData.value = [];
  rawBuddyData.value = [];
  await getBuddyList();
  refreshing.value = false;
};

const performSearch = () => {
  pagination.value.pageNo = 1;
  buddyData.value = [];
  rawBuddyData.value = [];
  getBuddyList();
};

const resetFilter = () => {
  filterState.value = {
    gender: 'all',
    distance: '',
    cost: '',
  };
};

const filterModalTop = ref('300rpx'); // 默认顶部位置

const toggleFilterModal = () => {
  if (!showFilterModal.value) {
    // 计算 tabs 的位置
    nextTick(() => {
      // #ifdef H5
      try {
        const tabsEl = document.querySelector('.tabs');
        if (tabsEl) {
          const rect = tabsEl.getBoundingClientRect();
          if (rect) {
            filterModalTop.value = `${rect.bottom}px`;
          } else {
            filterModalTop.value = '300rpx';
          }
        } else {
          // 默认值：spacer(100) + header-content(约100) + tabs(约100) = 约300rpx
          filterModalTop.value = '300rpx';
        }
      } catch (error) {
        console.error('获取tabs位置失败:', error);
        filterModalTop.value = '300rpx';
      }
      // #endif
      // #ifndef H5
      // APP和小程序端使用固定值
      filterModalTop.value = '300rpx';
      // #endif
    });
  }
  showFilterModal.value = !showFilterModal.value;
};

const confirmFilter = () => {
  showFilterModal.value = false;
  pagination.value.pageNo = 1;
  buddyData.value = [];
  rawBuddyData.value = [];
  getBuddyList();
};

const getCurrentLocation = () => {
  // #ifdef APP-PLUS
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      currentLatitude.value = res.latitude;
      currentLongitude.value = res.longitude;
      reverseGeocode(res.latitude, res.longitude);
      if (rawBuddyData.value.length > 0) {
        buddyData.value = rawBuddyData.value.map(mapBuddyData);
      }
    },
    fail: (err) => {
      console.error('定位失败:', err);
      currentLocation.value = '定位失败';
      currentLatitude.value = null;
      currentLongitude.value = null;
      uni.showToast({
        title: '定位失败，请检查定位权限',
        icon: 'none'
      });
    }
  });
  // #endif
};

const reverseGeocode = async (latitude, longitude) => {
  // #ifdef APP-PLUS
  const amapWebKey = 'b42db041e2d8c26c0b4bdd60f29d0fcb';
  
  try {
    
    const url = `https://restapi.amap.com/v3/geocode/regeo?key=${amapWebKey}&location=${longitude},${latitude}&radius=1000&extensions=all`;
    
    const response = await uni.request({
      url: url,
      method: 'GET'
    });
    
    if (response.statusCode === 200 && response.data.status === '1') {
      const result = response.data.regeocode;
      if (result && result.formatted_address) {
        currentLocation.value = result.formatted_address;
      } else if (result && result.addressComponent) {
        const addr = result.addressComponent;
        const address = (addr.province || '') + 
                       (addr.city || '') + 
                       (addr.district || '') + 
                       (addr.township || '') + 
                       (addr.street || '') + 
                       (addr.streetNumber || '');
        currentLocation.value = address || '未知位置';
      } else {
        currentLocation.value = '未知位置';
      }
    } else {
      console.error('逆地理编码失败:', response.data);
      currentLocation.value = '定位中...';
    }
  } catch (error) {
    console.error('逆地理编码请求失败:', error);
    currentLocation.value = '定位中...';
  }
  // #endif
};

watch(activeTab, () => {
  pagination.value.pageNo = 1;
  buddyData.value = [];
  rawBuddyData.value = [];
  getBuddyList();
});

watch(isMapMode, async (newVal) => {
  if (newVal) {
    await nextTick();
    setTimeout(() => {
      // #ifdef H5
      const mapContainer = document.querySelector('.map-container');
      const mapEl = document.getElementById('buddyMap');
      
      if (mapContainer && mapEl) {
        const viewportHeight = window.innerHeight;
        // 固定头部高度：spacer(100) + header-content(约100) + tabs(约100) + 间距(约100) = 约400rpx
        // 转换为px（假设1rpx = 0.5px）
        const fixedHeaderHeight = 200; // 400rpx ≈ 200px
        const calculatedHeight = viewportHeight - fixedHeaderHeight;
        
        mapContainer.style.top = `${fixedHeaderHeight}px`;
        mapContainer.style.height = `${calculatedHeight}px`;
        mapEl.style.height = `${calculatedHeight}px`;
        mapEl.style.width = '100%';
      }
      // #endif
    }, 300);
  }
});

onMounted(async () => {
  getCurrentLocation();
  await getBuddyTypeList();
  await getBuddyList();
  
  uni.$on('showPublishModal', () => {
    publishModalRef.value?.showModal && publishModalRef.value.showModal();
  });
  
  uni.$on('buddyOrderCreated', () => {
    onRefresh();
  });
})

onUnmounted(() => {
  uni.$off('showPublishModal');
  uni.$off('buddyOrderCreated');
})
</script>

<style lang="scss" scoped>
.map-container {
  position: absolute;
  top: 400rpx;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 0 17rpx 0 17rpx;
  box-sizing: border-box;
  display: flex;
  z-index: 50;
  overflow: hidden;
  background-color: transparent;
}

.buddy-map {
  width: 100%;
  height: 100%;
  border-radius: 20rpx 20rpx 0 0;
  position: relative;
  margin-top: 0;
}

/* 隐藏高德地图logo */
.buddy-map :deep(.amap-logo),
.buddy-map :deep(.amap-copyright) {
  display: none !important;
}

.buddy-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: calc(98rpx + env(safe-area-inset-bottom));
  padding-bottom: calc(98rpx + constant(safe-area-inset-bottom));
}

.header-image {
  position: absolute;
  width: 100%;
  height: 480rpx;
  top: 0;
  left: 0;
  z-index: 0;
}

.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background-color: transparent;
  padding-top: env(safe-area-inset-top);
  padding-top: constant(safe-area-inset-top);
}

.spacer {
  height: 100rpx;
  width: 100%;
  background-color: transparent;
}

.header-content {
  position: relative;
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-top: 20rpx;
  z-index: 1;
  
  .location {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #333;
    margin-right: 20rpx;
    min-width: 0;
    overflow: hidden;
    
    uni-icons {
      margin-right: 6rpx;
    }
    
    text {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
      flex: 1;
      min-width: 0;
    }
  }

  .search-bar-wrapper {
    flex: 0 0 auto;
    width: 300rpx;
    margin-right: 20rpx;
    margin-left: auto;
    
    .search-bar-container {
      display: flex;
      align-items: center;
      background-color: #fff;
      border-radius: 50rpx;
      padding: 0 20rpx;
      height: 60rpx;
      
      .search-input {
        flex: 1;
        height: 100%;
        font-size: 26rpx;
        color: #333;
        background: transparent;
        border: none;
        outline: none;
        
        &::placeholder {
          color: #999;
        }
      }
      
      .search-icon-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40rpx;
        height: 40rpx;
        margin-left: 10rpx;
      }
    }
  }

  .header-icons {
    display: flex;
    align-items: center;
    .mode-toggle-icon {
      width: 48rpx;
      height: 48rpx;
    }
  }
}

.tabs {
  width: 100%;
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-sizing: border-box;

  .tabs-scroll {
    flex: 1;
    min-width: 0;
    white-space: nowrap;
    overflow: hidden;
    
    .tabs-content {
      display: inline-flex;
      align-items: center;
      white-space: nowrap;
    }
  }

  .tab-item {
    padding: 10rpx 20rpx;
    margin-right: 20rpx;
    font-size: 30rpx;
    color: #000;
    border-radius: 30rpx;
    white-space: nowrap;
    flex-shrink: 0;

    &.active {
      color: #000;
      font-weight: bold;
    }
  }
  
  .filter-tab-icon {
    margin-left: 20rpx;
    flex-shrink: 0;
    width: 48rpx;
    height: 48rpx;
    flex: 0 0 48rpx;
  }
}

.buddy-list {
  position: relative;
  z-index: 20;
  flex: 1;
  overflow-y: auto;
  padding: 0 17rpx 120rpx;
  padding-top: 20rpx;
  box-sizing: border-box;
  /* 固定头部高度：spacer(100) + header-content(约100) + tabs(约100) = 约300rpx，增加一些额外间距 */
  margin-top: 300rpx;
  height: calc(100vh - 300rpx);
}

.loading-more,
.no-more {
  text-align: center;
  padding: 30rpx 0;
  font-size: 26rpx;
  color: #999;
}
</style>

<style lang="scss">
.buddy-list .uni-scroll-view-content {
  padding-right: 0 !important;
}

/* 筛选弹框 */
.filter-modal-overlay {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 0;
}

.filter-modal {
  width: 100%;
  background-color: #fff;
  border-radius: 0 0 20rpx 20rpx; /* 只有底部圆角 */
  padding: 30rpx 24rpx;
  max-height: calc(100vh - 200rpx);
  overflow-y: auto;
  margin-top: 0; /* 紧贴在蒙层顶部 */
}

.filter-section {
  margin-bottom: 30rpx;
  display: flex;
  align-items: flex-start;
  
  .filter-label {
    font-size: 28rpx;
    font-weight: 500;
    color: #333;
    margin-right: 30rpx;
    flex-shrink: 0;
    width: 80rpx;
  }
  
  .filter-options {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
  }
  
  .filter-option {
    padding: 10rpx 20rpx;
    border-radius: 30rpx;
    font-size: 26rpx;
    color: #999; /* 未选中时文字为灰色 */
    background-color: #f5f5f5;
    white-space: nowrap;
    transition: all 0.3s;
    
    &.filter-option-active {
      background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
      color: #fff;
    }
  }
}

.filter-footer {
  display: flex;
  gap: 60rpx;
  margin-top: 30rpx;
  padding-top: 24rpx;
  border-top: 1rpx solid #eee;
  justify-content: center;
  
  .filter-btn {
    width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    border-radius: 30rpx;
    font-size: 28rpx;
    
    &.filter-btn-reset {
      background-color: #f5f5f5;
      color: #333;
    }
    
    &.filter-btn-confirm {
      background: linear-gradient(90deg, #B276FF 0%, #74A7FF 100%);
      color: #fff;
    }
  }
}

/* 地图弹框 */
.map-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  box-sizing: border-box;
}

.map-modal-content {
  position: relative;
  width: 100%;
  max-width: 680rpx;
  max-height: 80vh;
  background-color: transparent;
  border-radius: 0;
  padding: 0;
  box-sizing: border-box;
  overflow-y: auto;
  animation: slideUp 0.3s ease-out;
  cursor: pointer;
}

.map-modal-buddy-card {
  pointer-events: auto;

  :deep(.buddy-card) {
    pointer-events: auto;
    cursor: pointer;
  }

  :deep(.buddy-card *) {
    pointer-events: auto;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.map-modal-close {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
}
</style>

<style lang="scss">
/* 全局隐藏高德地图logo */
.amap-logo,
.amap-copyright {
  display: none !important;
  opacity: 0 !important;
  visibility: hidden !important;
}

/* H5平台隐藏地图logo */
/* #ifdef H5 */
map {
  .amap-logo,
  .amap-copyright {
    display: none !important;
  }
}
/* #endif */
</style>